import React, { useState, useEffect } from 'react';
import { createPortal } from 'react-dom';
import { useI18n } from '@/utils/in18';

interface AgeVerificationModalProps {
    isOpen: boolean;
    onConfirm: () => void;
    onReject: () => void;
}

const AgeVerificationModal: React.FC<AgeVerificationModalProps> = ({
    isOpen,
    onConfirm,
    onReject
}) => {
    const [isVisible, setIsVisible] = useState(false);
    const { t } = useI18n();

    useEffect(() => {
        if (isOpen) {
            setIsVisible(true);
            // 防止背景滚动
            document.body.style.overflow = 'hidden';
        } else {
            document.body.style.overflow = 'unset';
        }

        return () => {
            document.body.style.overflow = 'unset';
        };
    }, [isOpen]);

    if (!isVisible) return null;

    const handleConfirm = () => {
        onConfirm();
        setIsVisible(false);
    };

    const handleReject = () => {
        onReject();
        setIsVisible(false);
    };

    const content = (
        <div className="fixed inset-0 z-[9999] flex items-center justify-center p-4">
            {/* 背景遮罩 - 更深的黑色背景 */}
            <div
                className="absolute inset-0"
                style={{
                    background: "rgba(9, 9, 11, 0.8)",
                    backdropFilter: "blur(12px)",
                    WebkitBackdropFilter: "blur(12px)" // 为了 Safari 兼容性
                }}
            />

            {/* 模态框内容 */}
            <div className="relative z-10 mx-auto inline-block max-w-[100%]">
                <div
                    className="relative rounded-3xl px-6 py-10 transform transition-all duration-300 ease-out"
                    style={{
                        background: '#09090B',
                        backdropFilter: 'blur(25px)',
                        border: '1px solid rgba(255, 255, 255, 0.08)',
                        boxShadow: `
              0 25px 50px -12px rgba(0, 0, 0, 0.6),
              0 0 0 1px rgba(255, 255, 255, 0.05),
              inset 0 1px 0 rgba(255, 255, 255, 0.1)
            `
                    }}
                >
                    {/* 品牌标题 */}
                    <div className="mb-8">
                        <h1
                            className="text-4xl font-bold mb-2 tracking-tight text-transparent bg-clip-text"
                            style={{
                                backgroundImage: 'linear-gradient(135deg, #ff6b9d 0%, #ff6b9d 25%, #ff6b9d 45%, #F1F1F1 65%, #F1F1F1 100%)',
                                backgroundRepeat: 'no-repeat',
                                // display: 'inline-block',
                                textAlign: 'center',
                                WebkitBackgroundClip: 'text',
                                WebkitTextFillColor: 'transparent',
                                backgroundClip: 'text',
                                filter: 'drop-shadow(0 0 10px rgba(255, 107, 157, 0.3))'
                            }}
                        >
                            Kales.ai
                        </h1>
                    </div>

                    {/* 主要内容 */}
                    <div className="mb-10">
                        <h2 className="md:text-xl text-lg font-semibold text-white mb-6 leading-relaxed text-left">
                            <span className="hidden md:inline">
                                {t('ageModal.subtitle_line1')}<br />
                                {t('ageModal.subtitle_line2')}
                            </span>
                        </h2>
                        <h3 className="md:text-xl text-[1.3rem] font-semibold text-white mb-6 leading-relaxed text-center">
                            {t('ageModal.subtitle_single')}
                        </h3>

                        <div className="mx-auto w-full md:max-w-[40rem] px-4">
                            <p
                                className="text-gray-300 text-[0.95rem] leading-relaxed text-left"
                                style={{
                                    wordBreak: 'normal',
                                    overflowWrap: 'normal',
                                    hyphens: 'none'
                                }}
                            >
                                {t('ageModal.consent_prefix')}
                                {t('ageModal.consent_suffix')}
                                <span
                                    className="text-gray-300 text-[0.95rem] font-semibold cursor-pointer hover:text-pink-200 transition-colors duration-200"
                                    onClick={() => {
                                        try { window.location.href = '/clause'; } catch (e) { window.open('/clause', '_blank'); }
                                    }}
                                >
                                    {t('ageModal.terms_link')}
                                </span>
                            </p>
                        </div>

                    </div>

                    {/* 按钮组 */}
                    <div className="space-y-4">
                        {/* 确认按钮 */}
                        <button
                            onClick={handleConfirm}
                            className="w-full py-4 px-6 rounded-lg font-semibold text-lg text-black transition-all duration-300 hover:scale-[1.02] hover:shadow-xl active:scale-[0.98] relative overflow-hidden group"
                            style={{
                                background: '#EC4899',
                                boxShadow: '0 8px 25px rgba(255, 107, 157, 0.4), 0 0 0 1px rgba(255, 255, 255, 0.1)'
                            }}
                        >
                            <span className="relative z-10">{t('ageModal.confirm_button')}</span>
                            <div
                                className="absolute inset-0 opacity-0 group-hover:opacity-20 transition-opacity duration-300"
                                style={{
                                    background: 'linear-gradient(135deg, rgba(255, 255, 255, 0.3) 0%, transparent 100%)'
                                }}
                            />
                        </button>

                        {/* 拒绝按钮 */}
                        <button
                            onClick={handleReject}
                            className="w-full py-4 px-6 rounded-lg font-semibold text-lg text-gray-300 border border-gray-600 hover:bg-gray-800/50 hover:border-gray-500 hover:text-white transition-all duration-300 hover:scale-[1.02] active:scale-[0.98]"
                            style={{
                                background: 'rgba(55, 55, 65, 0.3)',
                                backdropFilter: 'blur(10px)'
                            }}
                        >
                            {t('ageModal.reject_button')}
                        </button>
                    </div>
                </div>
            </div>
        </div>
    );

    const host = document.body;
    return host ? createPortal(content, host) : content;
};

// 年龄验证主机组件
const AgeVerificationHost: React.FC = () => {
    const [isModalOpen, setIsModalOpen] = useState(false);

    useEffect(() => {
        // 检查用户是否已经验证过年龄
        const hasVerified = localStorage.getItem('age_verified');

        if (!hasVerified) {
            // 延迟显示模态框，确保页面已加载
            const timer = setTimeout(() => {
                setIsModalOpen(true);
            }, 100);

            return () => clearTimeout(timer);
        }
    }, []);

    const handleConfirm = () => {
        // 用户确认年满18岁
        localStorage.setItem('age_verified', 'true');
        localStorage.setItem('age_verified_timestamp', Date.now().toString());
        setIsModalOpen(false);
    };

    const handleReject = () => {
        // 用户未满18岁，立即关闭网页（不再询问）
        try {
            // 首先尝试直接关闭当前标签页
            window.close();
        } catch (e) {
            // ignore
        }

        // 如果浏览器阻止关闭，则强制跳转到 about:blank
        setTimeout(() => {
            try {
                window.location.href = 'about:blank';
            } catch (e) {
                // 最后的降级：重写 document 的内容并禁用交互
                document.documentElement.innerHTML = '<html><head><meta charset="utf-8"><title>Closed</title></head><body></body></html>';
            }
        }, 50);
    };

    return (
        <AgeVerificationModal
            isOpen={isModalOpen}
            onConfirm={handleConfirm}
            onReject={handleReject}
        />
    );
};

export default AgeVerificationHost;